package edu.zjucst.spb.conf;

import edu.zjucst.spb.domain.ResponseResult;
import edu.zjucst.spb.enums.ResponseStatusEnum;
import edu.zjucst.spb.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author MrLi
 * @date 2022-12-03 21:53
 **/
@ControllerAdvice
@Slf4j
public class ProjExceptionHandler {

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResponseResult<Object> jsonErrorHandler(HttpServletRequest req, BizException e) throws Exception {
        ResponseResult<Object> r = new ResponseResult<>();
        r.setMsg(e.getRetMessage());
        r.setCode(e.getRetCode());
        r.setData(null);
        return r;
    }

//    @ExceptionHandler(value = NotLoginException.class)
//    @ResponseBody
//    public ResponseResult notLoginErrorHandler(HttpServletRequest req, SpbUserAccountException e) throws Exception {
//        ResponseResult r = new ResponseResult();
//        r.setMsg(e.getRetMessage());
//        r.setCode(e.getRetCode());
//        r.setData(null);
//        return r;
//    }

    /**
     * 登录认证异常
     */
    @ExceptionHandler({UnauthenticatedException.class, AuthenticationException.class})
    @ResponseBody
    public ResponseResult<Object> authenticationException() {
        ResponseResult<Object> r = new ResponseResult<>();
        r.setMsg(ResponseStatusEnum.AUTHENTICATION_ERROR.getDescription());
        r.setCode(ResponseStatusEnum.AUTHENTICATION_ERROR.getCode());
        r.setData(null);
        return r;
    }

    /**
     * 用户权限不足
     */
    @ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
    @ResponseBody
    public ResponseResult<Object> authorizationException() {
        ResponseResult<Object> r = new ResponseResult<>();
        r.setMsg(ResponseStatusEnum.AUTHORIZATION_FORBIDDEN.getDescription());
        r.setCode(ResponseStatusEnum.AUTHORIZATION_FORBIDDEN.getCode());
        r.setData(null);
        return r;
    }
}
